package HibernateNavi;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import nht.entity.TMap;
import nht.entity.TMapLang;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HelloHibernate {
	private static Session session;
	static {
		SessionFactory sessionFactory = HibernateConfig.getSessionFactory();
		session = sessionFactory.openSession();
	}

	public static void main(String[] args) {
		// saveRecord();
		// getListAll();
		// getList();
		// updateRecord();
		//getRecord();
		// updateList();
		getRecordInRelationship();
	}

	public static void saveRecord() {
		try {
			System.out.println("Inserting Record");
			for (int i = 0; i < 5; i++) {
				TMap tmap = new TMap(1, "my avatar", 1, 1, 1, new Date(),
						new Date());
				session.save(tmap);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.flush();
			session.close();
		}
	}

	public static void updateRecord() {
		// TMap map = (TMap)session.get(TMap.class,2);
		// System.out.println( "TMap (" + map.getId() + ") updated at: " +
		// map.getUpdatedAt() );
		// map.setInvalid((byte)0);
		// session.update(map);
		// session.flush();
		// session.close();
	}

	public static void getRecordInRelationship() {
		TMap map = (TMap) session.get(TMap.class, 1);
		System.out.println("==== Size ====   " + map.getLanguages().size());
		Set list = map.getLanguages();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object object = (Object) iterator.next();
			if (object instanceof TMapLang) {
				System.out.println(((TMapLang)object).getId().getLangCode());	
			}
		}

	}

	public static void getRecord() {
		TMap map = (TMap) session.get(TMap.class, 1);
		System.out.println("TMap (" + map.getId() + ") updated at: "
				+ map.getUpdatedAt());		
	}

	public static void getList() {
		session.beginTransaction();
		List result = session.createQuery("from TMap where id>10").list();
		for (TMap map : (List<TMap>) result) {
			System.out.println("TMap (" + map.getId() + ") updated at: "
					+ map.getUpdatedAt());
		}
		session.getTransaction().commit();
		session.close();
	}

	public static void getListAll() {
		session.beginTransaction();
		List result = session.createQuery("from TMap").list();
		System.out.println("===size ====:   " + result.size());
		for (TMap map : (List<TMap>) result) {
			System.out.println("TMap (" + map.getId() + ") updated at: "
					+ map.getUpdatedAt());
		}
		session.getTransaction().commit();
		session.close();
	}

	public static void updateList() {
		session.beginTransaction();
		String hqlUpdate = "update TMap set bgimg = :newImage where invalid = :invalidvalue";
		int updatedEntities = session.createQuery(hqlUpdate)
				.setString("newImage", "new avatar")
				.setInteger("invalidvalue", 1).executeUpdate();
		session.getTransaction().commit();
		session.close();
	}
}
